package cn.jetpiece.cloud.joss.api.config;

import cn.jetpiece.cloud.feign.instance.FeignInstance;
import cn.jetpiece.cloud.joss.api.basic.ConfigApi;
import cn.jetpiece.cloud.joss.api.config.properties.JossClientProperties;
import cn.jetpiece.cloud.model.util.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Joss客户端自动配置
 *
 * @author XuJZ
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = JossClientProperties.PREFIX, value = "enabled", havingValue = "true")
public class JossClientAutoConfig implements ApplicationRunner {

    @Bean
    @ConfigurationProperties(prefix = JossClientProperties.PREFIX)
    public JossClientProperties jossClientProperties() {
        JossClientProperties properties = new JossClientProperties();
        properties.setInstance(properties);
        return properties;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        ConfigApi configApi = null;
        try {
            configApi = SpringContextHolder.getBean(ConfigApi.class);
        } catch (Exception e) {
            log.warn("Not Local Joss ConfigApi Bean!");
        }
        if (configApi == null) {
            configApi = FeignInstance.getInstance().newInstance(ConfigApi.class, "jetpiece-joss");
        }
        JossClientProperties.getInstance().setBaseUrlPrefix(configApi.getBaseUrlPrefix());
    }
}
